// components/book/book.js
const app = getApp()
Component({
  // 使用自定义样式必须设置该值！！
  options: {
    styleIsolation: 'shared'
  },
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    inputShowed: false,
    inputVal: '',
    prePageY: null,
    types: []
  },

  lifetimes: {
    async attached () {
      wx.showLoading({
        title: '加载书籍中...',
      })
      const { result } = await wx.cloud.callFunction({
        name: 'loadTypes',
        data: {}
      })
      this.setData({
        handleSearch: this.handleSearch.bind(this),
        types: result.data
      })
      wx.hideLoading()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 控制搜索栏和 tab 栏的显示
    // 界面向下滑动则隐藏搜索栏，向上滑动则隐藏 tab 栏
    handleTouchStart (e) {
      const curPageY = e.changedTouches[0].pageY
      this.setData({
        prePageY: curPageY
      })
    },
    // 结束触碰时判断显示与否并重置环境
    handleTouchEnd (e) {
      const curPageY = e.changedTouches[0].pageY
      if (curPageY < this.data.prePageY) {
        this.triggerEvent('TabbarShow', {
          isTabbarShow: false,
          curIndex: 1
        }, {
          bubbles: true,
          composed: true
        })
      } else if (curPageY > this.data.prePageY) {
        this.triggerEvent('TabbarShow', {
          isTabbarShow: true,
          curIndex: 1
        }, {
          bubbles: true,
          composed: true
        })
      }
      this.setData({
        prePageY: null
      })
    },
    // 查找书籍函数
    handleSearch (value) {
      return new Promise((resolve, reject) => {
        setTimeout(async () => {
          if (value === '') {
            resolve([])
          }
          // 这里发请求查找
          const books = await wx.cloud.callFunction({
            name: 'searchBooks',
            data: {
              query: value
            }
          })
          // 如果返回是数组，说明是根据名称模糊查找
          if (Array.isArray(books.result)) {
            const searchList = []
            books.result.forEach(item => {
              searchList.push({
                text: item.bookName,
                value: item
              })
            })
            resolve(searchList)
          } else {
            // 如果返回不是数组，说明是根据编号查找
            resolve([{
              text: books.result.bookName,
              value: books.result
            }])
          }
        }, 200)
      })
    },
    // 选中查找结果的事件函数
    selectResult: function (e) {
      const data = e.detail.item.value
      const types = this.data.types
      wx.navigateTo({
        url: '/pages/bookDetail/bookDetail',
        event: {
          acceptData (data) {
            console.log(data)
          }
        },
        success (res) {
          res.eventChannel.emit('accepData', {
            data,
            operate: 'search',
            types
          })
        }
      })
    }
  }
})
